package mapper;

import lombok.Data;
import domain.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author if
 * Description: What is it?
 * date: 2021/6/18 上午 09:25
 */
@Data
public class QueryMapper<T> {
    private StringBuilder sql=null;
    private Map<String, Object> map;
    private Class<T> clazz;
    private int version=0;

    public QueryMapper(Class<T> clazz) {
        this.clazz=clazz;
        this.map=new HashMap<>();
    }

    public QueryMapper<T> or(){
        this.sql.append(" or ");
        this.version++;
        return this;
    }
    public void and(){
        this.sql.append(" and ");
        this.version++;
    }
    private void ifField(String key) throws NoSuchFieldException {
        try{
            this.clazz.getDeclaredField(key);
        }catch (NoSuchFieldException e){
            throw new NoSuchFieldException("未找到该属性 : "+key);
        }
    }
    public QueryMapper<T> allEq(Map<String, Object> params) throws NoSuchFieldException {
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            eq(key,params.get(key));
        }
        return this;
    }
    public QueryMapper<T> eq(String key,Object value){
        try {
            ifField(key);
            if(this.sql==null){
                sql=new StringBuilder(" where ");
            }
            if(this.map.size()>this.version){
                and();
            }
            this.map.put(key,value);

            this.sql.append(key).append(" = ");
            if(this.clazz.getDeclaredField(key).getType()==String.class){
                this.sql.append("'");
            }
            this.sql.append(value);
            if(this.clazz.getDeclaredField(key).getType()==String.class){
                this.sql.append("'");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return this;
    }
    public void clear(){
        this.sql.delete(0,this.sql.length());
        this.sql=null;
        this.clazz=null;
        map.clear();
    }
}
